package cn.kgc.vue.aspects;

import cn.hutool.json.JSONUtil;
import cn.kgc.vue.commons.KgcLogs;
import cn.kgc.vue.entity.LogInfo;
import cn.kgc.vue.service.LogInfoService;
import cn.kgc.vue.utils.IpUtil;
import cn.kgc.vue.utils.JWTUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * @author 课工场
 * @date 2023/12/16
 * @description
 */
@Aspect
@Component
public class LogAspect {

    @Resource
    private LogInfoService logInfoService;
    @Resource
    private JWTUtil jwtUtil;

    @Pointcut("@annotation(cn.kgc.vue.commons.KgcLogs)")
    public void pointCut(){};
    // 日志记录

    @Around("pointCut()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) {

        Object proceed = null;
        try {

            long start = System.currentTimeMillis();
            // 目标方法的执行
            proceed = joinPoint.proceed();
            long end = System.currentTimeMillis();
            Integer time = (int) (end - start);

            // 获取参数
            Object[] args = joinPoint.getArgs();
            String strArgs = JSONUtil.toJsonStr(args);

            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            KgcLogs annotation = method.getAnnotation(KgcLogs.class);
            String model = annotation.model();
            String operationInfo = annotation.operation().getOperationInfo();


            //  获取请求对象   request
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest req = requestAttributes.getRequest();

            String ip = IpUtil.getIp(req);
            String requestURI = req.getRequestURI();

            String token = req.getHeader("token");

            Map<String, Object> claims = jwtUtil.getClaims(token);
            String username  = (String) claims.get("username");

            // 封装数据  将数据写入 sys_log_info  数据库表
            LogInfo logInfo = new LogInfo();
            logInfo.setIp(ip);
            logInfo.setModel(model);
            logInfo.setParams(strArgs);
            logInfo.setUsername(username);
            logInfo.setUrl(requestURI);
            logInfo.setDescription(operationInfo);
            logInfo.setTimeConsuming(time);

            logInfoService.save(logInfo);

        } catch (Throwable e) {
            throw new RuntimeException(e);
        }


        return proceed;
    }


}
